#!/usr/bin/env python
#coding: utf8

from getpass import getpass
import hashlib

__version__ = 'v1.0.0'

'''
作业: 写一个密码验证程序,正确的密码在文本里,需要你去比对,输入的密码允许错误3次,超过3次报错.
      注意编码风格以及合理使用异常.
    
版本1：
    1、使用类实现用户管理的基本功能
    2、添加异常处理的方式
'''

DB_PATH = 'userdb'

def open_binary(fname, mode='rb'):
    '以二进制的方式打开文件'
    return open(fname, mode)

def md5_encrypt(field):
    '字段md5加密'
    try:
        return hashlib.md5(field).hexdigest()
    except TypeError as e:
        raise e

class Users(object):
    '''用户对象管理类'''
    def __init__(self, dbfile=DB_PATH):

        self._userdict = {}
        self._dbfile = dbfile

        try:
            with open_binary(self._dbfile) as fd:
                for line in fd:
                    if line:
                        user, passwd = line.split(':', 1)
                        self._userdict[user] = passwd.strip()
        except IOError as e:
            raise e
        
    def login(self, username, passwd):
        '用户登陆判断功能'
        passwd = md5_encrypt(passwd)
        if username in self._userdict.iterkeys() and \
            passwd == self._userdict.get(username):
            return True
        return False

    def add_user(self, username, passwd):
        '添加用户功能'
        if username in self._userdict.iterkeys():
            return False
        passwd = md5_encrypt(passwd)
        try:
            self._userdict[username] = passwd
            return True
        except TypeError:
            return False

    def del_user(self, username):
        '删除用户功能'
        try:
            del self._userdict[username]
            return True
        except KeyError:
            return False

if __name__ == '__main__':

    err_count = 0
    usermanger = Users()

    while err_count < 3:

        u = raw_input('Please enter your username: ')
        p = getpass('Please enter your password: ')
        result = usermanger.login(u, p)

        if result:
            print(
                '\033[32mLogin Sucess, {u}.\033[0m'.format(u=u)
            )
            break
        else:
            print(
                '\033[31mError: username or password error!\033[0m'
            )
        
        err_count += 1